package club.blueline.userapi.controller;

import club.blueline.userapi.entity.*;
import club.blueline.userapi.mapper.UserMapper;
import club.blueline.userapi.utils.ResultUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/api/user")
public class UserController {

    @Resource
    private UserMapper userMapper;
    private final BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();

    @GetMapping
    public Result getUsernameById(@RequestParam(value = "id") Integer id) {
        String username = userMapper.getUsernameById(id);
        if(username == null) {
            return ResultUtils.genFailResult("无此ID用户").setCode(ResultCode.FAIL.code());
        }
        return ResultUtils.genSuccessResult(username);
    }

    @GetMapping("/detail")
    public Result getUserDetailById(@RequestParam(value = "id") Integer id) {
        UserDetailDto detail = userMapper.getUserDetailById(id);
        if(detail == null) {
            return ResultUtils.genFailResult("无此ID用户").setCode(ResultCode.FAIL.code());
        }
        return ResultUtils.genSuccessResult(detail);
    }

    @PutMapping
    public Result editUserDetail(@RequestBody EditUserDetailDto userDetailDto) {
        boolean fail = false;
        if(userMapper.editUsername(userDetailDto.getId(), userDetailDto.getUsername()) != 1) {
            fail = true;
        }
        if(userMapper.editUserDetail(userDetailDto) != 1) {
            fail = true;
        }
        if(fail) {
            return ResultUtils.genFailResult("修改用户信息部分失败！").setCode(ResultCode.FAIL.code());
        }
        return ResultUtils.genSuccessResult();
    }

    @DeleteMapping
    public Result deleteUser(@RequestParam(value = "id") Integer id) {
        if(userMapper.deleteUser(id) != 1) {
            return ResultUtils.genFailResult("删除用户失败！").setCode(ResultCode.FAIL.code());
        }
        return ResultUtils.genSuccessResult();
    }

    @PostMapping("/changePass")
    public Result changePassword(Integer id, String password) {
        if(userMapper.changePassword(id, bCryptPasswordEncoder.encode(password)) != 1) {
            return ResultUtils.genFailResult("修改密码失败！").setCode(ResultCode.FAIL.code());
        }
        return ResultUtils.genSuccessResult();
    }

    @GetMapping("/list")
    public Result listUserInfo() {
        List<UserInfoDo> list = userMapper.getAll();
        if(list == null) {
            return ResultUtils.genFailResult("查询失败！").setCode(ResultCode.FAIL.code());
        }
        return ResultUtils.genSuccessResult(list);
    }

}
